// app.js

document.getElementById('loginForm').addEventListener('submit', async (event) => {
    event.preventDefault();

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        const response = await fetch('http://localhost:9876/user/dologin', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password })
        });

        console.log('Response:', response)
        // 解析响应数据
        const saResult = await response.json();

        // 检查登录是否成功
        if (saResult.code === 200) { // 假设 200 表示成功
            const token = saResult.data.token; // 获取 token
            const websocketUrl = saResult.data.websocketUrl; // 获取 WebSocket 地址

            // 将 token 存储在本地
            localStorage.setItem('token', token);

            // 登录成功后，连接 WebSocket
            connectWebSocket(websocketUrl);

            // 显示登录成功状态
            document.getElementById('status').innerText = '登录成功';
        } else {
            throw new Error(saResult.message || '登录失败');
        }
    } catch (error) {
        console.error(error);
        document.getElementById('status').innerText = '登录失败: ' + error.message;
    }
});

function connectWebSocket(url) {
    const token = localStorage.getItem('token');
    const socket = new WebSocket(`${url}?token=${token}`);

    socket.onopen = () => {
        console.log('WebSocket connection established');
        document.getElementById('status').innerText = 'WebSocket 连接已建立';
    };

    socket.onmessage = (event) => {
        console.log('Message from server:', event.data);
        const messagesDiv = document.getElementById('messages');
        const messageElement = document.createElement('div');
        messageElement.innerText = event.data;
        messagesDiv.appendChild(messageElement);
    };

    socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        document.getElementById('status').innerText = 'WebSocket 错误: ' + error.message;
    };

    socket.onclose = () => {
        console.log('WebSocket connection closed');
        document.getElementById('status').innerText = 'WebSocket 连接已关闭';
    };
}
